import React, { useState, useEffect, useRef, useCallback } from "react";
import Loading from "../../components/Loading/loading.jsx";
import BottomLoading from "../../components/BottomLoading/bottom-loading.jsx";
import MusicList from "../../components/MusicList/music-list.jsx";
import playmvIcon from "../../assets/images/playmv.svg";
import { connect } from "react-redux";

import {
  /** 导入样式组件 */
  SearchWrapper,
  InputWrapper,
  HotWordWrapper,
  SearchRemdWord,
  MatchListWrapper
} from "./style";
import {
  /** 导入actions */
  getHotWrodsAction,
  getSuggestAction,
  getSearchResult,
  clearSearchResult
} from "./store/action";
const limit = 20;
function Search(props) {
  const [keyword, setKeyword] = useState(""); // 搜索的关键字
  const [loaded, setLoaded] = useState(false); //
  const offsetRef = useRef(); // 偏移量

  const [isLoading, setIsLoading] = useState(false);
  const [loadNone, setloadNone] = useState(false);
  const len = keyword.trim().length; // 输入关键字的长度
  const {
    /** 从props中解构出数据 */
    getHotWrodsAction,
    getSearchResult,
    getSuggestAction,
    clearSearchResult,
    search
  } = props;
  /** 挂载完成请求热门词，组件销毁时，清除搜索结果数据 */
  useEffect(() => {
    getHotWrodsAction(keyword);
    offsetRef.current = 0;
    return () => {
      clearSearchResult();
    };
  }, []);
  /** 解构出 searchState数据 */
  const { hotWords, searchResult, searchSuggestWords } = search;
  /** 用useEffect 根据输入关键字请求建议词，依赖于关键字，关键词改变执行，如果关键字长度为0，则清除结果数据 */
  useEffect(() => {
    let timer = setTimeout(() => {
      setloadNone(false);
      if (!!len) {
        getSuggestAction(keyword);
      } else {
        /** 这里判断第一次进入，如果没有搜索结果的话，不清除，减少一次render */
        const lens = searchResult.songs.length + searchResult.matchs.length;
        setIsLoading(false);
        if (lens) {
          clearSearchResult();
        }
      }
    }, 100);
    return () => {
      clearTimeout(timer);
    };
  }, [keyword]);
  /** 在结果监视结果数组，有数据则结束loading状态 */
  useEffect(() => {
    setloadNone(false);
    if (searchResult.matchs.length + searchResult.songs.length) {
      setIsLoading(false);
    } else {
      setloadNone(true);
    }
    /** 是否加载完毕判断 */
    const count = searchResult.songs.songCount;
    const currentSongs = searchResult.songs.length;
    if (count <= currentSongs) {
      setLoaded(true);
    } else {
      setLoaded(false);
    }
  }, [searchResult]);

  /** 处理点击热门词和搜索历史，发情请求 */
  const handleSearch = useCallback(key => {
    setloadNone(false);
    setIsLoading(true); // 设置loading状态
    offsetRef.current = 0;
    if (searchResult.length) {
      clearSearchResult(); // 清空最佳匹配
    }
    setKeyword(key); // 设置关键词
    getSearchResult(key, offsetRef.current, limit); // 执行搜索action
  });
  // 下拉到底监听事件,到底加载更多
  const handleScroll = () => {
    const count = searchResult.songs.songCount;
    const currentSongslen = searchResult.songs.length;
    /** 当歌曲总数大于当前以加载的歌曲数量时，就触发加载更多，否则显示加自完毕 */
    if (count >= currentSongslen) {
      offsetRef.current = currentSongslen + 1;
      getSearchResult(keyword, offsetRef.current, limit);
    } else {
      setLoaded(true);
    }
  };
  return (
    <SearchWrapper className="toTop">
      <InputWrapper>
        <div className="s">
          <i className="iconfont icon-search"></i>
          <input
            maxLength={38}
            placeholder="搜索歌曲、歌手、专辑"
            value={keyword}
            onChange={e => setKeyword(e.target.value)}
            onFocus={() => {
              clearSearchResult();
              setloadNone(false);
              setIsLoading(false);
            }}
          />
          {len ? (
            <i className="iconfont icon-cuo" onClick={() => setKeyword("")}></i>
          ) : null}
        </div>
      </InputWrapper>
      <Loading show={isLoading} loadNone={loadNone} />
      {searchResult.songs.length ? (
        <div className="result-wrapper">
          <MatchListWrapper playIcon={playmvIcon}>
            <h3>最佳匹配</h3> 
            <ul>
              {searchResult.matchs.map(item => (
                <li className={`border-bottom match-item ${item.type || ""}`} key={item.id}>
                  <div className="cover">
                    <figure>
                      <img
                        className="pic"
                        width={item.type === "mv" ? null : "50"}
                        height="50"
                        src={item.picUrl || item.cover}
                        alt=""
                      />
                    </figure>
                    <article>
                      <h4 className="dot">
                        <span>
                          {item.type === "mv"
                            ? "MV:"
                            : item.type === "artist"
                            ? "歌手:"
                            : item.type === "album"
                            ? "专辑:"
                            : ""}
                        </span>{" "}
                        {item.name}
                      </h4>
                      <p className="overflow-dot">
                        {item.artistName || item.artist?.name}
                      </p>
                    </article>
                    <i className="iconfont icon-right"></i>
                  </div>
                </li>
              ))}
            </ul>
          </MatchListWrapper>
          <MusicList
            onscroll={{ is: true, callback: handleScroll, fieldHeight: 10 }}
            list={searchResult.songs}
          />
          <BottomLoading loaded={loaded} />
        </div>
      ) : (
        <div>
          {!len ? (
            <HotWordWrapper>
              <section>
                <h3 className="title">热门搜索</h3>
                <ul className="list">
                  {hotWords.map(item => (
                    <li
                      key={item.first}
                      className="list-item border"
                      onClick={handleSearch.bind(this, item.first)}
                    >
                      <span>{item.first}</span>
                    </li>
                  ))}
                </ul>
              </section>
            </HotWordWrapper>
          ) : !isLoading ? (
            <SearchRemdWord>
              <h3 onClick={handleSearch.bind(this, keyword)}>
                搜索 “{keyword}”
              </h3>
              <ul>
                {searchSuggestWords.map(item => (
                  <li
                    className="remd-item"
                    key={item.keyword}
                    onClick={handleSearch.bind(this, item.keyword)}
                  >
                    <i className="iconfont icon-search"></i>
                    <span className="dot">{item.keyword}</span>
                  </li>
                ))}
              </ul>
            </SearchRemdWord>
          ) : null}
        </div>
      )}
    </SearchWrapper>
  );
}

// 用 connect 连接redux
export default connect(
  state => ({ search: state.search /** 拿到search中的state */ }),
  {
    // 拿到action
    getHotWrodsAction,
    getSearchResult,
    getSuggestAction,
    clearSearchResult
  }
)(React.memo(Search));
